import { useState, useEffect, useCallback, useRef } from 'react';

interface UserData {
  visitor_uuid: string;
  user_avatar: string;
  visitor_token: string;
  login_type: string;
  user_email: string;
  user_displayName: string;
  last_chat_type?: string;
  vip_live?: number | null;
  tokens_balance?: number;
}

interface UseAuthReturn {
  isLoggedIn: boolean;
  userData: UserData | null;
  showLoginModal: boolean;
  isRegisterMode: boolean;
  checkLoginAndShowModal: () => boolean;
  openLoginModal: (isRegister?: boolean) => void;
  closeLoginModal: () => void;
  handleLoginSuccess: () => void;
  logout: () => void;
  refreshUserData: () => void; // 新增刷新用户数据函数
}

export const useAuth = (): UseAuthReturn => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userData, setUserData] = useState<UserData | null>(null);
  const [showLoginModal, setShowLoginModal] = useState(false);
  const [isRegisterMode, setIsRegisterMode] = useState(false);

  // 使用ref来跟踪是否已经初始化，防止重复检查
  const isInitialized = useRef(false);
  const lastUserDataRef = useRef<string | null>(null);

  // 检查登录状态
  const checkLoginStatus = useCallback(() => {
    try {
      const userDataStr = localStorage.getItem('userData');

      // 如果数据没有变化，跳过处理
      if (userDataStr === lastUserDataRef.current && isInitialized.current) {
        return isLoggedIn;
      }

      lastUserDataRef.current = userDataStr;

      if (userDataStr) {
        const parsedUserData = JSON.parse(userDataStr);
        // console.log('useAuth: 检查到localStorage中的用户数据 - vip_live:', parsedUserData.vip_live);
        // console.log('useAuth: 检查到localStorage中的用户数据 - tokens_balance:', parsedUserData.tokens_balance);
        setUserData(parsedUserData);
        setIsLoggedIn(true);
        isInitialized.current = true;
        return true;
      } else {
        setUserData(null);
        setIsLoggedIn(false);
        isInitialized.current = true;
        return false;
      }
    } catch (error) {
      console.error('Failed to parse user data:', error);
      setUserData(null);
      setIsLoggedIn(false);
      isInitialized.current = true;
      return false;
    }
  }, []); // 🔧 移除 [isLoggedIn] 依赖，避免循环依赖

  // 检查登录状态，如果未登录则显示登录弹窗
  const checkLoginAndShowModal = useCallback((isRegister = false) => {
    const loggedIn = checkLoginStatus();
    if (!loggedIn) {
      setIsRegisterMode(isRegister);
      setShowLoginModal(true);
    }
    return loggedIn;
  }, [checkLoginStatus]);

  // 打开登录弹窗
  const openLoginModal = useCallback((isRegister = false) => {
    setIsRegisterMode(isRegister);
    setShowLoginModal(true);
  }, []);

  // 关闭登录弹窗
  const closeLoginModal = useCallback(() => {
    setShowLoginModal(false);
  }, []);

  // 登录成功处理
  const handleLoginSuccess = useCallback(() => {
    // 重置初始化状态，强制重新检查
    isInitialized.current = false;
    lastUserDataRef.current = null;

    checkLoginStatus();
    setShowLoginModal(false);

    // 触发自定义事件通知其他组件登录状态变化
    try {
      window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));
    } catch (error) {
      // console.warn('触发登录状态变化事件失败:', error);
      console.error('trigger login status change event failed', error);
    }
  }, [checkLoginStatus]);

  // 登出
  const logout = useCallback(() => {
    try {
      // 清除用户相关的localStorage数据
      const keysToRemove = [
        'userData', 'visitor_uuid', 'visitor_token', 'user_avatar',
        'user_email', 'user_displayName', 'login_type', 'last_chat_type',
        'pending_chat_id', 'chat_history_list', 'AiPersioninfor', 'HomeList'
      ];

      keysToRemove.forEach(key => {
        localStorage.removeItem(key);
      });

      // 清除所有以特定前缀开头的聊天记录
      Object.keys(localStorage).forEach(key => {
        if (key.startsWith('chat_history_') || key.startsWith('ai_person_') || key.startsWith('bg_image_')) {
          localStorage.removeItem(key);
        }
      });

      // 重置状态
      setUserData(null);
      setIsLoggedIn(false);
      isInitialized.current = false;
      lastUserDataRef.current = null;

      // 触发自定义事件通知其他组件登录状态变化
      try {
        window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));
      } catch (error) {
        // console.warn('触发登录状态变化事件失败:', error);
        console.error('trigger login status change event failed', error);
      }
    } catch (error) {
      // console.error('登出过程中出错:', error);
      console.error('logout failed', error);
    }
  }, []);

  // 刷新用户数据
  const refreshUserData = useCallback(() => {
    // 重置初始化状态，强制重新检查
    isInitialized.current = false;
    lastUserDataRef.current = null;
    checkLoginStatus();
  }, [checkLoginStatus]);

  // 组件挂载时检查登录状态 - 只执行一次
  useEffect(() => {
    if (!isInitialized.current) {
      checkLoginStatus();
    }
  }, []); // 空依赖数组，只在挂载时执行一次

  // 监听 localStorage 变化和自定义登录状态变化事件
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      // 只处理userData的变化，避免不必要的检查
      if (e.key === 'userData' && e.newValue !== lastUserDataRef.current) {
        // 延迟检查，避免快速连续的变化
        setTimeout(() => {
          checkLoginStatus();
        }, 100);
      }
    };

    const handleLoginStatusChange = () => {
      console.log('useAuth: 接收到userLoginStatusChanged事件');
      // 延迟检查，避免快速连续的事件
      setTimeout(() => {
        console.log('useAuth: 开始检查登录状态更新');
        checkLoginStatus();
      }, 100);
    };

    // 添加事件监听器
    window.addEventListener('storage', handleStorageChange);
    window.addEventListener('userLoginStatusChanged', handleLoginStatusChange);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
      window.removeEventListener('userLoginStatusChanged', handleLoginStatusChange);
    };
  }, [checkLoginStatus]); // 只依赖稳定的checkLoginStatus

  return {
    isLoggedIn,
    userData,
    showLoginModal,
    isRegisterMode,
    checkLoginAndShowModal,
    openLoginModal,
    closeLoginModal,
    handleLoginSuccess,
    logout,
    refreshUserData,
  };
}; 